/**
 * @Author: guo-bomin 2974463764@qq.com
 * @Date: 2023-12-15 12:43:17
 * @LastEditors: guo-bomin 2974463764@qq.com
 * @LastEditTime: 2023-12-15 15:01:55
 * @FilePath: \NodeJs\wechat-test\app\service\ernie.js
 * @Description: 郭博民16670506200
 * @有问题微信同号询问，急事call我
 * @Copyright (c) 2023 by 湖南習羽网络科技有限公司, All Rights Reserved.
 */
const { Service } = require("egg");

class ErnieService extends Service {
  async getAccessToken() {
    console.log(
      "===================ErnieService getAccessToken====================="
    );
    let ctx = this.ctx;

    try {
      const res = await ctx.curl(
        `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${ctx.app.config.ernie.client_id}&client_secret=${ctx.app.config.ernie.client_secret}`,
        {
          method: "GET",
          rejectUnauthorized: false,
          data: {},
          headers: {},
          timeout: 30000,
          contentType: "json",
          dataType: "json",
        }
      );
      console.log(res);

      if (res.data.access_token) {
        ctx.app.config.ernie.access_token = res.data.access_token;
        console.log("access_token", ctx.app.config.ernie.access_token);
      }
    } catch (error) {
      console.log(error);
    }
  }
  async sendMsg(msg) {
    console.log('===================ErnieService sendMsg=====================');
    let ctx = this.ctx;
    try {
        const res = await ctx.curl(
            `https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=${ctx.app.config.ernie.access_token}`, {
                method: 'POST',
                rejectUnauthorized: false,
                data: {
                    "messages": msg
                },
                timeout: 30000,
                contentType: 'json',
                dataType: 'json',
            })
        // console.log(res)

        if (res.data) {
            return res.data;
        }
        return null;
    } catch (error) {
        console.log(error)
        return null;
    }
}
}

module.exports = ErnieService;
